package com.yyl.render.render

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.yyl.render.utils.AssetsUtils
import java.io.IOException
import java.nio.ByteBuffer

class ArgbRender : BaseRender() {

    val syncLock = Object()
    var context: Context? = null
    override fun onStartRender(context: Context) {
        this.context = context
        nativeSetProgramType(ProgramTypeVideo)
        nativeLoadShaderScript(ShaderVertex, AssetsUtils.load(context, "shader/image.vert"))
        nativeLoadShaderScript(ShaderFragment, AssetsUtils.load(context, "shader/image.frag"))
    }

    fun updateRGBA(
        width: Int,
        height: Int,
        data: ByteArray
    ) {
        synchronized(syncLock) {
            if (isWaiting()) {
                // nativeUpdateFrame(IMAGE_FORMAT_RGBA,width, height, data)
//                val bitmap = getBitmapFromRgb565(data, width, height)
//                val buf = ByteBuffer.allocate(bitmap.byteCount)
//                bitmap.copyPixelsToBuffer(buf)
//                val byteArray = buf.array()
//                nativeUpdateFrame(IMAGE_FORMAT_RGBA, bitmap.width, bitmap.height, byteArray)
                loadRGBAImage()
                requestRender()
            }
        }
    }

    fun getBitmapFromRgb565(data: ByteArray, w: Int, h: Int): Bitmap {
        val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565)
        val buffer = ByteBuffer.wrap(data)
        bitmap.copyPixelsFromBuffer(buffer)
        return bitmap
    }

    fun loadRGBAImage() {
        val inputStream = context?.assets?.open("demo/front.jpg") ?: return
        try {
            val bitmap = BitmapFactory.decodeStream(inputStream)
            if (bitmap != null) {
                val buf = ByteBuffer.allocate(bitmap.byteCount)
                bitmap.copyPixelsToBuffer(buf)
                val byteArray = buf.array()
                nativeUpdateFrame(
                    IMAGE_FORMAT_RGBA,
                    bitmap.width,
                    bitmap.height,
                    byteArray
                )
            }
        } finally {
            try {
                inputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}
